/*
 * Copyright 2011-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.system.user.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.google.common.base.Strings;

import me.ijleex.mgmt.commons.util.MathUtils;
import me.ijleex.mgmt.framework.constant.Constants;
import me.ijleex.mgmt.framework.entity.Result;
import me.ijleex.mgmt.system.user.entity.User;
import me.ijleex.mgmt.system.user.entity.UserRole;
import me.ijleex.mgmt.system.user.mapper.UserMapper;
import me.ijleex.mgmt.system.user.mapper.UserRoleMapper;
import me.ijleex.mgmt.system.user.service.IUserRoleService;

/**
 * 用户&角色关系 服务层实现
 *
 * @author liym
 * @since 2019-03-14 11:43:16 By 'codegen'
 */
@Service
public class UserRoleServiceImpl implements IUserRoleService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UserRoleMapper mapper;
    private final UserMapper userMapper;

    public UserRoleServiceImpl(UserRoleMapper mapper, UserMapper userMapper) {
        this.mapper = mapper;
        this.userMapper = userMapper;
    }

    @Override
    public List<Long> getRoleIdByUserId(Long userId) {
        return this.mapper.selectRoleIdByUserId(userId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result grant(UserRole object) {
        Long userId = object.getUserId();
        if (MathUtils.isNullOrZero(userId)) {
            return Result.invalidArg("用户编号不能为空：userId");
        }
        this.logger.debug("为用户【{}】分配角色", userId);

        User user = this.userMapper.selectById(userId);
        if (user == null) {
            return Result.error("用户不存在：" + userId);
        }

        String roleIds = object.getRoleIds();
        if (Strings.isNullOrEmpty(roleIds)) {
            // 如果角色id为空，则删除已分配的角色

            this.logger.warn("为用户分配角色时，待分配的角色为空，则删除用户原有的角色");

            int x = this.mapper.deleteByUserId(userId);
            if (x == 0) {
                return Result.error("删除用户已有的角色失败：" + userId);
            } else {
                // TODO 清除缓存
                return Result.ok(userId);
            }
        } else {
            this.logger.debug("为用户分配角色，先删除用户原有的角色");

            // 授权之前，删除以前授权的数据
            this.mapper.deleteByUserId(userId);

            String[] roleIdArr = roleIds.split(Constants.DELIMITER);
            try {
                int count = 0;
                for (String roleId : roleIdArr) {
                    object.setRoleId(Long.parseLong(roleId));
                    // 设置 remarks 的值为用户名，方便删除时使用
                    object.setRemarks(user.getUsername());
                    count += this.mapper.insert(object);
                }
                return Result.ok("为用户分配角色成功：" + userId + "，角色个数：" + count);
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                this.logger.error("为用户分配角色失败", e);
                return Result.error("用户授权失败");
            }
        }
    }

}
